<!--分组选择器groupBar-->
<!--
参数isFloat 是否是鼠标移上去展示
isFloat为true 需要传入方法setSearchPop 和setSearchPopOut
参考LayoutGroup组件

-->
<template>
  <div
    class="pop-search"
    @mouseleave="setSearchPopOut(false)"
    @mouseenter="setSearchPop"
  >
    <a-auto-complete
      class="global-search"
      :placeholder="$t('groupmanger.keyword')"
      option-label-prop="title"
      v-model="searchTreeVal"
      @select="getSearchNode"
      @search="searchTreeSelect"
      @blur="clearSearchSelect"
      @mouseenter="setSearchPop"
    >
      <template
        slot="dataSource"
        @mouseenter="setSearchPop"
        @mouseover="setSearchPop"
      >
        <a-select-option
          @mouseenter="setSearchPop"
          @mouseover="setSearchPop"
          v-for="item in searchSelect"
          :key="`${item.groupId}`"
          :title="item.groupId"
        >
          {{ item.title }}
        </a-select-option>
      </template>
      <a-input>
        <a-button slot="suffix" style="margin-right: -12px" class="search-btn">
          <a-icon type="search" />
        </a-button>
      </a-input>
    </a-auto-complete>

    <!-- <a-tree
      class="seltree-sel"
      :tree-data="groupTreeData"
      @select="onSelectTree"
      :load-data="onLoadTreeData"
      :expandedKeys="expandedKeys"
      :selectedKeys="treeVal"
      @expand="expandTree"
      :showIcon="true"
      ref="treeRef"
    >
      <a-icon slot="switcherIcon" type="down" />
      <icon-font slot="location" type="ic-tree-group" />
      <icon-font slot="building" type="ic-tree-network" />
      <icon-font slot="device" type="ic-tree-device" />
    </a-tree> -->
    <rj-group-tree
      class="seltree-sel"
      :tree-data="groupTreeData"
      @select="onSelectTree"
      :load-data="onLoadTreeData"
      :expandedKeys="expandedKeys"
      :selectedKeys="treeVal"
      @expand="expandTree"
      :showIcon="true"
      ref="treeRef"
    >
      <a-icon slot="switcherIcon" type="down" />
      <icon-font slot="location" type="ic-tree-group" />
      <icon-font slot="building" type="ic-tree-network" />
      <icon-font slot="device" type="ic-tree-device" />
    </rj-group-tree>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import RjGroupTree from '../rj-group-tree/index.vue';
export default {
  name: 'rj-group',
  props: {
    isFloat: {
      //是否是浮动弹框
      type: Boolean,
      default: false,
    },
    selectGroupType: {
      type: [Array, String],
      default: 'ALL',
    },
    groupId: {
      //是否是全选
      type: Number,
      default: 0,
    },
    showGroupType: {
      //显示的节点类型['ROOT','LOCATION','BUILDING','DEVICE']
      type: [Array, String],
      default: 'ALL',
    },
    searchType: {
      //用于搜索用的
      type: String,
      default: 'ALL',
    },
  },
  components: {
    RjGroupTree,
  },
  data() {
    return {
      groupTreeData: [],
      newgroupTreeData: [],
      currentGroupId: '',
      allTreeMap: [],
      searchActive: false,
      // exitNowGroup: null,
      firstGroup: '',
      searchTreeVal: [],
      searchSelect: [],
      searchTime: null,
      groupName: '',
      expandedKeys: [],
      treeVal: [],
    };
  },
  activated() {},
  computed: {
    ...mapState('Group', ['groupTree']),
  },
  created() {
    this.dealGroupTree();
  },

  watch: {
    groupId(val) {
      let groupId = val;
      let type = this.allTreeMap[groupId]?.type;
      if (
        //判断传入的groupid是否是可选的
        (this.selectGroupType != 'ALL' &&
          this.selectGroupType.indexOf(type) == -1) ||
        groupId == 0
      ) {
        console.log('this.firstGroup?.groupId', this.firstGroup?.groupId);
        groupId = this.firstGroup?.groupId;

        this.$emit('getCurrentGroupInfo', this.allTreeMap[groupId]);
      }
      this.currentGroupId = groupId;
      this.treeVal = [this.currentGroupId];
      this.groupName = this.allTreeMap[this.currentGroupId]?.title;
      this.setTreeNodeData(this.currentGroupId);
    },
    groupTree() {
      this.firstGroup = null;
      this.dealGroupTree();
    },
    showGroupType(val) {
      this.dealGroupTree();
      // let groups = this.groupTree;
      // this.groupTreeData = this.mapTreeData(groups.subGroups);
    },
  },
  methods: {
    setSearchPop() {
      if (this.isFloat) {
        this.$emit('setSearchPop');
      }
    },
    setSearchPopOut(isClose) {
      if (this.isFloat) {
        this.$emit('setSearchPopOut', isClose);
      }
    },
    dealGroupTree() {
      this.allTreeMap = [];
      let groups = this.groupTree;
      if (!groups) {
        return;
      }
      this.mapTreeData(groups.subGroups);
      let rootGroupId = groups.subGroups[0].groupId;
      this.rootGroupId = rootGroupId;
      let groupTreeData = [];
      for (let i = 0; i < groups.subGroups.length; i++) {
        //过滤掉不显示的分组类型
        if (
          this.showGroupType != 'ALL' &&
          this.showGroupType.indexOf(groups.subGroups[i].type) == -1
        ) {
          continue;
        }
        let id = groups.subGroups[i].groupId;
        let node = this.allTreeMap[id];
        let node1 = { ...node };
        groupTreeData.push(node1);
      }
      this.groupTreeData = groupTreeData;
      if (this.expandedKeys.length == 0 && groupTreeData.length > 0) {
        this.expandedKeys = [this.groupTreeData[0].groupId];
      } else {
        for (let i = 0; i < this.expandedKeys.length; i++) {
          let group = this.expandedKeys[i];

          if (this.allTreeMap[group] && this.allTreeMap[group].children) {
            let newGroupId = this.allTreeMap[group].children[0].groupId;
            this.setTreeNodeData(newGroupId);
          }
        }
      }
      if (this.currentGroupId == '') {
        if (process.env.VUE_APP_MACC_ENV !== 'INTL') {
          this.currentGroupId =
            this.groupId && this.allTreeMap[this.groupId]
              ? this.groupId
              : this.firstGroup.groupId;
        } else {
          this.currentGroupId = sessionStorage.getItem('maccGroupId');
        }
      }
      let currentGroupId = this.currentGroupId;
      //页面从支出设备分组DEVICE到不支持时 选择的groupid需要变化
      if (
        !this.showGroupType.includes('DEVICE') &&
        this.allTreeMap[currentGroupId] &&
        this.allTreeMap[currentGroupId].type == 'DEVICE'
      ) {
        this.currentGroupId = this.allTreeMap[currentGroupId].pId;
        console.log(this.allTreeMap[currentGroupId]);
        this.changeGroupId(true);
      } else {
        if (process.env.VUE_APP_MACC_ENV == 'INTL') {
          // 因路由页面加载完后，无法获取到相应的全局信息（调接口要用到），所以在此改为true，方便获取数据 第一个true为是否触发，第二个true为是否初始化路由页面
          this.changeGroupId(true, true);
        } else {
          this.changeGroupId(true);
        }
      }
    },
    mapTreeData(data, parentNode) {
      let newData = [];
      let nodeData = [];
      // let groupId = this.groupId;
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (
          this.selectGroupType.indexOf(item.type) != -1 ||
          this.selectGroupType === 'ALL'
        ) {
          if (!this.firstGroup) {
            this.firstGroup = item;
          }
        }
        let node = { ...item };
        node.value = item.name;
        node.key = item.groupId;
        node.id = item.groupId;
        node.title = item.name;
        node.subGroups = null;
        node.selectable = false;
        if (parentNode) {
          node.pId = parentNode.groupId;
        } else {
          node.pId = '0';
        }
        if (this.selectGroupType === 'ALL') {
          node.selectable = true;
        } else {
          node.selectable =
            this.selectGroupType.indexOf(item.type) != -1 ? true : false;
        }
        if (['ROOT', 'LOCATION'].indexOf(item.type) != -1) {
          node.slots = { icon: 'location' };
        } else if (item.type == 'BUILDING') {
          node.slots = { icon: 'building' };
        } else {
          node.slots = { icon: 'device' };
        }
        //根据配置过滤节点
        const subGroup =
          this.showGroupType === 'ALL'
            ? item.subGroups
            : item.subGroups.filter((item) => {
                return this.showGroupType.indexOf(item.type) != -1;
              });
        //是否有符合条件的子节点
        if (subGroup && subGroup.length > 0) {
          // node.selectable = true;
          node.isLeaf = false;
        } else {
          node.isLeaf = true;
        }
        if (item.subGroups.length > 0) {
          this.mapTreeData(item.subGroups, node);
        }

        if (!this.allTreeMap[node.groupId]) {
          this.allTreeMap[node.groupId] = {
            ...node,
          };
        }
        if (
          this.showGroupType == 'ALL' ||
          this.showGroupType.indexOf(node.type) != -1
        ) {
          nodeData.push(node);
          newData.push(node);
          if (parentNode) {
            if (!this.allTreeMap[parentNode.groupId]) {
              this.allTreeMap[parentNode.groupId] = {};
              this.allTreeMap[parentNode.groupId] = { ...parentNode };
            }
            this.allTreeMap[parentNode.groupId].children = nodeData;
          }
        }
      }
      return newData;
    },
    onSelectTree(selectedKeys) {
      if (selectedKeys.length > 0) {
        this.currentGroupId = selectedKeys[0];
        this.changeGroupId(true);
        console.log('onSelectTree=======================');
        if (this.isFloat) {
          this.$emit('setSearchPopOut', true);
        }
      }
    },
    //对所有的组进行搜索
    searchTreeSelect(val) {
      if (this.searchTime) {
        clearTimeout(this.searchTime);
      }
      let self = this;
      this.searchTime = setTimeout(() => {
        if (val) {
          let selData = [];
          self.searchSelect = [];
          for (let i = 0; i < self.allTreeMap.length; i++) {
            if (self.allTreeMap[i]) {
              let item = self.allTreeMap[i];
              let name = item.name || '';
              name = name.toLowerCase();
              let val1 = val.toLowerCase();
              if (name.includes(val1)) {
                if (
                  this.searchType == 'ALL' ||
                  (this.searchType != 'ALL' && item.type == 'BUILDING')
                )
                  selData.push(item);
              }
            }
          }

          self.searchSelect = selData;
        }
      }, 500);
    },
    //清空搜索框
    clearSearchSelect() {
      this.searchSelect = [];
      this.searchTreeVal = [];
    },
    //搜索框选中后需要更新值
    getSearchNode(option) {
      console.log('getSearchNode');
      this.searchTreeVal = [];
      if (option) {
        let groupId = parseInt(option);
        this.currentGroupId = groupId;
        this.changeGroupId(true);
        this.setSearchPopOut(true);
        this.scrollToNode(option);
      }
    },
    changeGroupId(isEmit, initRoutePage) {
      let item = this.allTreeMap[this.currentGroupId];
      let isChange = false;
      if (!this.allTreeMap[this.currentGroupId]) {
        //有可能删除了网络更新，默认选中根节点
        this.currentGroupId = this.firstGroup.groupId;
        isChange = true;
      } else if (
        //判断传入的groupid是否是可选的
        this.selectGroupType != 'ALL' &&
        this.selectGroupType.indexOf(item.type) == -1
      ) {
        this.currentGroupId = this.firstGroup.groupId;
        isChange = true;
      }
      let newInfo = this.allTreeMap[this.currentGroupId];

      newInfo = { ...newInfo };
      if (!newInfo) {
        return;
      }
      this.groupName = newInfo.name;
      this.treeVal = [newInfo.groupId];
      if (newInfo) {
        newInfo.subGroups = null;
        newInfo.children = null;
        if (isEmit || isChange) {
          this.$emit('getCurrentGroupInfo', newInfo, initRoutePage);

          this.$iframeMsg('MACC3_CHANGE_GROUP', {
            groupInfo: newInfo,
          });
        }
        this.setTreeNodeData(newInfo.groupId);
      }
    },
    //自动滚动，将节点滚动到可视区域中间
    scrollToNode(option) {
      const el = this.$refs.treeRef.$el;
      if (this.allTreeMap[option]) {
        const title = this.allTreeMap[option].title;
        const treeWrapper = el.querySelector(
          `.ant-tree-node-content-wrapper[title="${title}"]`
        );

        if (treeWrapper) {
          treeWrapper.scrollIntoView({
            block: 'center',
          });
        }
      }
    },
    //获取当期分组信息
    getCurrentGroupInfo() {
      let groupId = this.rootGroupId;
      if (this.currentGroupId) {
        groupId = this.currentGroupId;
      }
      return this.allTreeMap[groupId];
    },

    //获取指定分组的分组信息
    getGroupInfo(groupId) {
      if (!groupId) return;
      return this.allTreeMap[groupId];
    },
    //异步加载树控件节点
    onLoadTreeData(treeNode) {
      if (treeNode.dataRef.isLeaf) {
        return;
      }
      return new Promise((resolve) => {
        const { groupId } = treeNode.dataRef;

        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        let children = this.allTreeMap[groupId].children;
        treeNode.dataRef.children = children;
        resolve();
      });
    },
    //设置树控件的节点
    setTreeNodeData(groupId) {
      let groupTreeData = this.groupTreeData.concat();
      this.findParentNode(groupId, groupTreeData);
      this.groupTreeData = groupTreeData;
    },
    //根据子节点的名称查找父节点 将遍历的节点加到树控件的原始数据中 置顶寻找已经的节点
    findParentNode(groupId, appTreeData1) {
      if (this.rootGroupId == groupId) {
        return;
      }
      if (this.allTreeMap[groupId]) {
        let node = this.allTreeMap[groupId];
        let currentNode = this.getCurrentNode(appTreeData1, node);
        let parentNode = null;
        if (!currentNode) {
          let expandedKeys = [];
          while (!currentNode) {
            //添加子节点的父节点
            parentNode = this.allTreeMap[node.pId];
            if (!parentNode) return;
            expandedKeys.push(node.pId);
            if (parentNode && parentNode.groupId == this.rootGroupId) {
              currentNode = true;
            } else {
              currentNode = this.getCurrentNode(appTreeData1, parentNode);
              if (currentNode) {
                currentNode = parentNode;
              }
              node = parentNode;
            }
          }
          let newArr = expandedKeys.map((value, index, arr) => value);
          this.expandedKeys = newArr;
        }
      }
    },
    //根据title循环遍历是否存在 存在的话返回当前node
    getCurrentNode(node, searchNode) {
      let isExit = false;
      for (let i = 0; i < node.length; i++) {
        if (searchNode && node[i].groupId == searchNode.groupId) {
          //查找到当前node
          node[i] = searchNode;
          break;
        }
      }
      if (!isExit) {
        for (let i = 0; i < node.length; i++) {
          if (node[i].children) {
            isExit = this.getCurrentNode(node[i].children, searchNode);
          }
          if (isExit) {
            break;
          }
        }
      }
      return isExit;
    },
    expandTree(expandedKeys) {
      this.expandedKeys = expandedKeys;
    },
  },
};
</script>

<style lang="less" scoped>
.ant-select-switcher-icon {
  font-size: 16px !important;
}
.group-bar {
  border-radius: 4px;
  background: #fff;
  height: 50px;
  line-height: 50px;
  text-align: left;
  z-index: 20;
}

.seltree-sel {
  height: 450px;
  overflow: auto;
}
.pop-search {
  background: #fff;
  border: 1px solid #d9d9d9;
  width: 100%;
  border-radius: 4px;
  padding-top: 8px;
  flex: 1;
  // position: absolute;
  z-index: inherit;
  padding-left: 8px;
  /deep/ .ant-tree li .ant-tree-node-content-wrapper {
    padding: 0;
  }
}
</style>

<style>
.global-search-wrapper {
  padding-right: 50px;
}

.global-search {
  /* width: 100%; */
  width: calc(100% - 46px - 8px);
}

.global-search.ant-select-auto-complete .ant-select-selection--single {
  margin-right: -46px;
}

.global-search.ant-select-auto-complete
  .ant-input-affix-wrapper
  .ant-input:not(:last-child) {
  padding-right: 62px;
}

.global-search.ant-select-auto-complete
  .ant-input-affix-wrapper
  .ant-input-suffix
  button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.global-search-item {
  display: flex;
}

.global-search-item-desc {
  flex: auto;
  text-overflow: ellipsis;
  overflow: hidden;
}

.global-search-item-count {
  flex: none;
}
</style>
